package cn.zhoujing.ssedemo;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;


@Slf4j
public class SseSession {

    /**
     * 用于存储所有的用户信息
     */
    private static Map<String, SseEmitter> sessionMap = new ConcurrentHashMap<>();

    /**
     * 添加用户
     *
     * @param sessionKey 用户id
     * @param sseEmitter 消息发射器
     */
    public static void add(String sessionKey, SseEmitter sseEmitter) {
        if (sessionMap.get(sessionKey) != null) {
            log.error("用户已存在");
            throw new RuntimeException("User exists!");
        }
        sessionMap.put(sessionKey, sseEmitter);
    }

    /**
     * 获取用户是否已存在
     *
     * @param sessionKey 用户id
     * @return
     */
    public static boolean exists(String sessionKey) {
        return sessionMap.get(sessionKey) != null;
    }

    /**
     * 删除用户信息
     *
     * @param sessionKey 用户id
     * @return
     */
    public static boolean remove(String sessionKey) {
        SseEmitter sseEmitter = sessionMap.get(sessionKey);
        if (sseEmitter != null) {
            sseEmitter.complete();
        }
        return false;
    }

    /**
     * 异常事件
     *
     * @param sessionKey 用户id
     * @param throwable  异常信息
     */
    public static void onError(String sessionKey, Throwable throwable) {
        SseEmitter sseEmitter = sessionMap.get(sessionKey);
        if (sseEmitter != null) {
            sseEmitter.completeWithError(throwable);
        }
    }

    /**
     * 发送消息
     *
     * @param sessionKey 用户id
     * @param content    消息内容
     * @throws IOException
     */
    public static void send(String sessionKey, String content) throws IOException {
        sessionMap.get(sessionKey).send(content);
    }

}

